#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#include "hash.h"

unsigned int hash(const char *key)
{
    unsigned int hash = 0;
    while(*key)
    {
        hash = (hash * 31 + *key++) % TABLE_SIZE;
    }
    return hash;

}

HashTable* hash_create_table(unsigned char *status)
{

    HashTable *table = (HashTable*)malloc(sizeof(HashTable));
    if(table)
        *status = 1;
    else
        *status = 0;
    return table;
}

void hash_insert_table(HashTable *table,const char *key,int value)
{

    unsigned int index = hash(key);
    HashNode *node = table->buckets[index];
    /*If the node has already been initialized, find the node and reassign it*/
    while(node)
    {
        if(strcmp(node->key,key) == 0)
        {
            node->value = value;
            return;
        }
        node = node->next;
    }
    /*else create node insert link list head*/
    node = (HashNode*)malloc(sizeof(HashNode));
    node->key = strdup(key);
    node->value = value;
    node->next = table->buckets[index];
    table->buckets[index] = node;
}

int* hash_search_node(HashTable *table,const char *key)
{
    unsigned int index = hash(key);
    HashNode *node = table->buckets[index];

    while(node)
    {
        if(strcmp(node->key,key) == 0)
        {
            return &(node->value);
        }
        node = node->next;

    }
    return NULL;
}

void hash_delete_node(HashTable *table,const char *key)
{
    unsigned int index = hash(key);
    HashNode *node = table->buckets[index];
    HashNode *prev = NULL;
    while(node)
    {
        if(strcmp(node->key,key) == 0)
        {
            if(prev)
                prev->next = node->next;
            else
                table->buckets[index] = node->next;    
            free(node->key);
            free(node);
            return ;
        }
        prev = node;
        node = node->next;
    }
}

